//
//  KABRegisterVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/1/16.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABRegisterVC.h"
#import <UINavigationBar+Awesome.h>
#import "UIColor+XDHex.h"
#import "GlobalHeader.h"
#import "ApiManager.h"
#import "XDAFNetworking.h"
#import "MBProgressHUD+XDPrompt.h"
#import "XDRsa.h"
#import "KABModel.h"
#import "KABUserAgreementVC.h"
#import "KABAboutUsVC.h"

@interface KABRegisterVC ()

@property (weak, nonatomic) IBOutlet UITextField *phoneNumTextField;
@property (weak, nonatomic) IBOutlet UITextField *verifyCodeTextField;
@property (weak, nonatomic) IBOutlet UITextField *pwdTextField;
@property (weak, nonatomic) IBOutlet UIButton *getVerifyBtn;
@property (weak, nonatomic) IBOutlet UIButton *submitBtn;
@property (weak, nonatomic) IBOutlet UIButton *checkBtn;
@property (weak, nonatomic) IBOutlet UIButton *protocolBtn;

@property (nonatomic, assign) KABRegisterVCType viewType;

@end

@implementation KABRegisterVC

#pragma mark - life cycle
- (instancetype)initWithViewType:(KABRegisterVCType)type {
    self = [super init];
    if (self) {
        _viewType = type;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    NSArray *titleArray = @[@"注册", @"找回密码", @"绑定手机"];
    self.navigationItem.title = titleArray[self.viewType];
}

- (void)initSubViews {
    NSDictionary *dic = @{NSForegroundColorAttributeName : [UIColor xd_colorWithHex:KABGlobalColorLoginFontColor],
                          NSFontAttributeName : [UIFont systemFontOfSize:14]};
    self.phoneNumTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入手机号" attributes:dic];
    self.verifyCodeTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入验证码" attributes:dic];
    self.pwdTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"密码6-20位" attributes:dic];
    
    [self.getVerifyBtn addTarget:self action:@selector(getVerifyBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    self.submitBtn.layer.masksToBounds = YES;
    self.submitBtn.layer.cornerRadius = CGRectGetHeight(self.submitBtn.frame) / 2.0;
    NSArray *submitBtnTitleArray = @[@"注册", @"确认", @"绑定"];
    [self.submitBtn setTitle:submitBtnTitleArray[self.viewType] forState:UIControlStateNormal];
    [self.submitBtn addTarget:self action:@selector(submitBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    self.checkBtn.hidden = (self.viewType != KABRegisterVCTypeRegister);
    [self.checkBtn addTarget:self action:@selector(checkBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    self.protocolBtn.hidden = (self.viewType != KABRegisterVCTypeRegister);
    [self.protocolBtn addTarget:self action:@selector(protocolBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor clearColor]];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar lt_reset];
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - delegate

#pragma mark - event response
- (void)getVerifyBtnTapped:(UIButton *)btn {
    // 校验手机号
    if (![self checkPhoneNum]) {
        return;
    }
    
    // 倒计时
    [self startTime];
    
    // 请求网络
    [self requestVerifyCode];
}

- (void)checkBtnTapped:(UIButton *)btn {
    btn.selected = !btn.selected;
//    KABAboutUsVC *vc = [[KABAboutUsVC alloc] init];
//    [self.navigationController pushViewController:vc animated:YES];
}

- (void)protocolBtnTapped:(UIButton *)btn {
    KABUserAgreementVC *vc = [[KABUserAgreementVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)submitBtnTapped:(UIButton *)btn {
    if ((self.viewType == KABRegisterVCTypeRegister) && !self.checkBtn.selected) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请同意Kabu用户协议"];
        return;
    }
    
    if (![self checkPhoneNum] || ![self checkVerifyCodeAndPwd]) {
        return;
    }
    
    if (self.viewType == KABRegisterVCTypeRegister) {
        [self requestRegister];
    } else if (self.viewType == KABRegisterVCTypeFindPwd) {
        [self requestForgetPassword];
    } else if (self.viewType == KABRegisterVCTypeBindPhone) {
        [self requestBindPhone];
    }
}

#pragma mark - private methods
- (BOOL)checkPhoneNum {
    if (self.phoneNumTextField.text.length != KABGlobalPhoneNumLength) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入11位数的手机号"];
        return NO;
    }
    
    return YES;
}

- (BOOL)checkVerifyCodeAndPwd {
    if (self.verifyCodeTextField.text.length != KABGlobalVerifyCodeLength) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入4位验证码"];
        return NO;
    }
    
    if (self.pwdTextField.text.length < KABGlobalPwdMinLength
        || self.pwdTextField.text.length > KABGlobalPwdMaxLength) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"密码长度为6-20位"];
        return NO;
    }
    
    return YES;
}

- (void)startTime{
    __block int timeout = 59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0),1.0 * NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
//                [self.verifCodeBtn setBackgroundColor:TCYP_COLOR_Xf7ba7f(1.0)];
                [self.getVerifyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                self.getVerifyBtn.userInteractionEnabled = YES;
            });
        }else{
            int seconds = timeout % 60 ;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                //NSLog(@"____%@",strTime);
                //                [UIView beginAnimations:nil context:nil];
                //                [UIView setAnimationDuration:1];
//                [self.getVerifyBtn setBackgroundColor:[UIColor grayColor]];
                [self.getVerifyBtn setTitle:[NSString stringWithFormat:@"已发送(%@)", strTime] forState:UIControlStateNormal];
                //                [UIView commitAnimations];
                self.getVerifyBtn.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

- (NSDictionary *)prepareParameters {
    NSInteger timestramp = [[NSDate date] timeIntervalSince1970];
    NSDictionary *dic = @{@"password" : self.pwdTextField.text,
                          @"timestamp": @(timestramp)};
    NSString *token = [XDRsa base64EncryptWithDictionary:dic];
    
    NSDictionary *parameters = @{@"account"  : self.phoneNumTextField.text,
                                 @"token"    : token,
                                 @"checkcode": self.verifyCodeTextField.text};
    
    return parameters;
}

- (void)exitViewController {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)exitToLoginVC {
    if (self.completeHandle) {
        self.completeHandle(self.phoneNumTextField.text);
        self.completeHandle = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - network request
- (void)requestVerifyCode {
    NSDictionary *parameters = @{@"phone_number" : self.phoneNumTextField.text};
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiCheckCode] parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求验证码返回成功:%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] != 200) {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestRegister {
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSDictionary *parameters = [self prepareParameters];
    
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiRegister] parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"注册返回成功：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [[KABModel sharedInstance] loginModelWithDictionary:responseObject];
            [[KABModel sharedInstance] saveUserInfoWithPwd:self.pwdTextField.text];
            [self exitViewController];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"注册失败：%@", error.localizedDescription);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestForgetPassword {
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSDictionary *parameters = [self prepareParameters];
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiForgetPassword] parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"找回密码成功：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            // 返回登录界面
            [[KABModel sharedInstance] saveUserInfoWithPwd:self.pwdTextField.text];
            [self exitToLoginVC];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"找回密码失败：%@", error.localizedDescription);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestBindPhone {
    // 发布Cos需要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    // 密码加密
    NSInteger timestramp = [[NSDate date] timeIntervalSince1970];
    NSDictionary *dic = @{@"password" : self.pwdTextField.text,
                          @"timestamp": @(timestramp)};
    NSString *token = [XDRsa base64EncryptWithDictionary:dic];
    NSDictionary *parameters = @{@"phone_number"  : self.phoneNumTextField.text,
                                 @"check_code": self.verifyCodeTextField.text,
                                 @"user_id" : @([KABModel sharedInstance].userInfo.uid),
                                 @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                                 @"token" : token};
    
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiBindPhone] parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"注册返回成功：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            MBProgressHUD *hud = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"修改手机成功"];
            hud.completionBlock = ^(){
                [self exitToLoginVC];
            };
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"注册失败：%@", error.localizedDescription);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}
#pragma mark - getters and setters

@end
